package com.ydy.data.service.impl;

import com.ydy.common.model.Permissions;
import com.ydy.common.util.CodeUtil;
import com.ydy.common.util.PageHelperUtils;
import com.ydy.common.vo.PageInfo;
import com.ydy.data.mapper.PermissionInfoMapper;
import com.ydy.data.mapper.RoleInfoMapper;
import com.ydy.data.service.PermissionInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PermissionInfoServiceImpl implements PermissionInfoService {

    @Autowired
    private PermissionInfoMapper permissionInfoMapper;

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Override
    public List<Permissions> queryPermissionInfo(Permissions permissions, PageInfo pageInfo) {
        PageHelperUtils.startPage(pageInfo);
        return permissionInfoMapper.queryPermissionInfo(permissions,pageInfo);
    }

    @Override
    public void submitPermissionInfo(Permissions permissions) {
        String permissionCode = permissions.getPermissionCode();
        if(StringUtils.isEmpty(permissionCode)){
            //查询
            List<Permissions> list = permissionInfoMapper.queryPermissionInfo(permissions,new PageInfo());
            if(CollectionUtils.isEmpty(list)){
                //插入
                permissions.setPermissionCode(CodeUtil.getCode());
                permissionInfoMapper.insertPermissionInfo(permissions);
            }else{
                throw new RuntimeException("该权限已存在，请重试！");
            }

        }else{
            //修改
            permissionInfoMapper.updatePermissionInfo(permissions);

        }

    }

    @Override
    @Transactional
    public void deletePermissionInfo(String permissionCode) {
        permissionInfoMapper.deletePermissionInfo(permissionCode);
        //删除角色权限
        roleInfoMapper.deleteRolePermissionInfo(null,permissionCode);

    }
}
